<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail','Network/Email');

class PostManageController extends AppController {
	var $helpers = array('Paginator','Html');
	public $user = "";
	var $components = array('Link','Files','Images','Strings');
	public function beforeFilter() {
		parent::beforeFilter();
		$this->user = parent::checkAdminOrManagerLogin();
	}
	/**
	* hiển thị toàn bộ tin, chưa dc check
	*/
	public function admin_index() {
		$this -> loadModel('Post');
		$conditions = array("Post.check_status" => UN_CHECKED_STATUS);
		$this->paginate = array(
                                'limit' => ITEM_PER_PAGE,
                                'order' => array('id' => 'desc'),
                             );
        $data = $this->paginate("Post",$conditions);
		$data = $this->addTimePostColumn($data);
        $this->set("data",$data);
		$this->set("title_for_layout","Tin chưa duyệt");
	}
	public function delete(){
		$this -> loadModel('Post');
		$this -> loadModel('Image');
		if ($this -> request -> is('post')) {
			//try{
				$id = $this -> request->data['value'];
				$checked = $this -> request->data['checked'];
				 $data = $this->Post->findByIdAndCheckStatus($id, $checked);
				 
				 $path = WWW_ROOT.$data['Post']['image_icon'];
				 $this->Files -> deleteFile($path);
				 
				 if(!empty($data)){
				 	 $images = $this->Image->findAllByPostId($id);
					 foreach ($images as $i) {
						$path = WWW_ROOT.$i['Image']['url'];
						$this->Files -> deleteFile($path);
					 }
					 //$this->Image->deleteAll($images);
					 $this->Post->delete($id, false);
					 $this->Image->deleteAll(array('Image.post_id' => $id), false);
					
					 	echo json_encode(array('success'=>'1'));
						exit;
					
				 }
			/*}catch(exception $e){
				echo json_encode(array('success'=>'2'));
				exit;
			}*/
		}
		echo json_encode(array('success'=>'2'));
		exit;
	}
	
	public function checkStatus(){
		$this -> loadModel('Post');
		if ($this -> request -> is('post')) {
			 $id = $this -> request->data['value'];
			 $data = $this->Post->findByIdAndCheckStatus($id, UN_CHECKED_STATUS);
			 if(!empty($data)){
			 	 $data['Post']['check_status'] = CHECKED_STATUS;
				 $data['Post']['updated_by'] = $this->user['id'];
				 $data['Post']['updated_at'] = date("Y-m-d H:i:s");
				 if($this->Post->save($data)){
					try {
						//gởi email thong bao tin da duoc duyet
						$email = new CakeEmail();
						$email->config('default')
						->to(array($data['Post']['mail_address']=>'Khách Hàng'))
						->subject('Tin đăng đã được duyệt')
						->send("Xin chào Quý khách!\nTin đăng của bạn đã được duyệt và được đăng trên http://maytot.vn , hãy vào website http://maytot.vn để theo dõi tin đăng của bạn. \nCám ơn bạn đã ghé thăm website của chúng tôi, hẹn gặp lại !\nEmail hỗ trợ: hotro@maytot.vn");
					} catch (Exception $e) {
						//loi gửi email 
					}
				 	echo json_encode(array('success'=>'1'));
					exit;
				 }
			 }
		}
		echo json_encode(array('success'=>'2'));
		exit;
	}
	public function admin_view(){
		$this->set("title_for_layout","Tin đã duyệt");
		$this -> loadModel('Post');
		$conditions = array("Post.check_status" => CHECKED_STATUS);
		$this->paginate = array(
                                'limit' => ITEM_PER_PAGE,
                                'order' => array('id' => 'desc'),
                             );
        $data = $this->paginate("Post",$conditions);
		$data = $this->addTimePostColumn($data);
        $this->set("data",$data);
	}
	
	public function admin_edit($id){
		$this->theme = 'Default';
		$this -> layout = 'layoutNoMenuLeft';
		
		
		$this->set("action","/admin/PostManage/edit");
		$this->loadModel('RootCategory');
		$this->loadModel('Region');
		$this->loadModel('Post');
		$this->loadModel('Image');
		
		$this->set('rootCategories',$this -> RootCategory->findAllData());
		$this->set('regions',$this -> Region->findAllData());
		$this->set('title_for_layout','Chỉnh sửa tin');
		
		$data = $this->Post->findById($id);
		if(empty($data)){
			$this->redirect(array('action' => 'index'));
		}
		$this->set("data",$data);
		$this->set("img",$this->Image->findAllByPostId($id));
		if ($this -> request -> is('post')) {
			$update = $this -> data;
			$update['id'] = $id;
			$update['title_vn'] = $this->Strings->replaceHTMLTag($update['title_vn']);
			$update['title_en'] = $this->Link->vietnamese_permalink($update['title_vn'], " ");
			$update['price'] = str_replace(",", "", $update['price']);
			$update['product_country'] = $this->Strings->replaceHTMLTag($update['product_country']);
			$update['content'] = $this->Strings->replaceHTMLTag($update['content']);
			$update['sell_name'] = $this->Strings->replaceHTMLTag($update['sell_name']);
			$update['updated_at'] = date("Y-m-d H:i:s");
			if ($this -> Post -> save($update)){
				$postID= $id;
				$imgList = $update['img'];
				$imgNew= array();
				foreach ($imgList as $i) {
					$img = array();
					if(!empty($i['id']) || !empty($i['url']) ){
						
						$img['post_id'] = $postID;
						$img['deleted'] = 0;
						$img['created_by'] = $this->user['id'];//lấy id của user login
						$img['created_at'] = date("Y-m-d H:i:s");
						$img['updated_by'] = $this->user['id'];//lấy id của user login
						$img['updated_at'] = date("Y-m-d H:i:s");
						if(isset($i['id'])){
							$img['id']=$i['id'];
						}
						if(!empty($i['url'])){
							$img['url']=$i['url'];
						}
						if(!empty($i['id']) && empty($i['url'])){
							$img['deleted'] = 1;
						}
							
						array_push($imgNew, $img);
					}
				}
				if(count($imgNew)>0){
					
					$this->Image->saveMany($imgNew);
				}
				$this->redirect(array('action' => 'index'));
			}
		}
		//end
		$this -> render('/PostingFree/edit');
	}
	/**
	 * up top tin đăng user
	 */
 	public function admin_uptop($id = null, $page){
 		$this->loadModel('Post');
		
		$this->Post->id = $id;
		if(!$this->Post->exists()){
			$this->redirect(array('action' => $page));
		}
		$date = date('Y/m/d H:i:s', time());
 		$this->Post->saveField('updated_at',$date);
		$this->Session->setFlash("Up TOP tin thành công");
 		$this->redirect(array('action' => $page));
 	}
/**
	 * Add time post column for lists
	 *
	 * @author VuLee
	 */
	private function addTimePostColumn($data){
		for ($i=0; $i < count($data); $i++) { 
			$data[$i]['Post']['time_post'] = $this->calculateTimePost($data[$i]['Post']['updated_at']);
		}
		return $data;
	}

	/**
	 * Calculate time post
	 *
	 * @author VuLee
	 */
	private function calculateTimePost($old_date){
		date_default_timezone_set('Asia/Ho_Chi_Minh');
		$current_date = date('Y-m-d H:i:s');
		$old_date = date_create($old_date);

		$current_date = date_create($current_date);
		$diff = date_diff($old_date, $current_date);

		$year = $diff->y;
		if ($year > 0) {
			return $year." năm";
		}

		$month = $diff->m;
		if ($month > 0) {
			return $month." tháng";
		}

		$day = $diff->d;
		if ($day > 0) {
			return $day." ngày";
		}

		$hour = $diff->h;
		if ($hour > 0) {
			return $hour." giờ";
		}

		$minute = $diff->i;
		$hour = $diff->h;
		if ($minute > 0) {
			return $minute." phút";
		}
		return "Mới đây";
	}
}
?>